package com.example.demo01.utils;


import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCPGUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    /**
     * 文件的读取，只需要读取一次就可以拿到这些值
     * */
    static {
        //0-获取配置文件资源的路径
//        ClassLoader classLoader = Object.class.getClassLoader();
//        URL resource = classLoader.getResource("jdbc.properties");
        //读取资源文件
        //1-Properties集合类
        Properties properties=new Properties();
        try {
            //F:\myNotes\Java\JavaWeb\Spring Boot\demoes\demo01\src\main\resources\static\postgresqlConfig\jdbcpg.properties
            properties.load(new FileReader("src/main/resources/static/postgresqlConfig/jdbcpg.properties"));
           // properties.load(new FileReader(resource.getPath()));
            //2-读取文件内容
            url=properties.getProperty("url");
            user=properties.getProperty("user");
            password=properties.getProperty("password");
            driver=properties.getProperty("driver");
            //3-注册驱动类
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 释放数据库连接资源的方法
     * */
    public static void close(Statement statement, Connection connection){
        if (statement!=null)
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        if (connection!=null)
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

    /**
     * 重载：释放数据库连接资源的方法
     * */
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        if (resultSet!=null)
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        if (statement!=null)
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        if (connection!=null)
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

}
